package com.ruix.app.ui.main;

import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.liaoinstan.springview.container.DefaultFooter;
import com.liaoinstan.springview.container.DefaultHeader;
import com.liaoinstan.springview.widget.SpringView;
import com.ruix.app.R;
import com.ruix.app.cache.CacheFactory;
import com.ruix.app.manager.UserManager;
import com.ruix.app.mapper.MessageListMapper;
import com.ruix.app.model.MessageModel;
import com.ruix.app.network.CacheObserver;
import com.ruix.app.network.RXObserver;
import com.ruix.app.network.RequestFactory;
import com.ruix.app.ui.adapter.MessageListAdapter;
import com.ruix.app.ui.base.BaseFragment;
import com.ruix.app.ui.message.MessagePostActivity;
import com.ruix.app.ui.message.MessageReportActivity;
import com.ruix.app.util.LogUitl;

import org.json.JSONObject;

import java.util.ArrayList;

import io.reactivex.disposables.Disposable;

/**
 * Created by hadexs on 2017/4/10.
 */

public class MessageFragment extends BaseFragment implements View.OnClickListener, AdapterView.OnItemClickListener,SwipeRefreshLayout.OnRefreshListener {


    private MessageListAdapter adapter;
    private ListView messageList;
    private SpringView springView;
    private TextView noMessageTip;
    private SwipeRefreshLayout mRefreshLayout;

    private int LOAD_COUNT = 20;


    @Override
    protected int loadViewLayout() {
        return R.layout.fragment_message;
    }

    @Override
    protected void initView() {
        mRefreshLayout = (SwipeRefreshLayout) mFragmentView.findViewById(R.id.refresh_layout);
        mRefreshLayout.setColorSchemeResources(R.color.bg_nav_default
                , R.color.bg_nav_yellow
                , R.color.bg_default
                , R.color.text_color_pink);

        messageList = (ListView) mFragmentView.findViewById(R.id.message_list);
        adapter = new MessageListAdapter(this.getActivity());
        messageList.setAdapter(adapter);
        springView = (SpringView) mFragmentView.findViewById(R.id.spring_view);
        springView.setType(SpringView.Type.FOLLOW);
        springView.setGive(SpringView.Give.BOTTOM);
//        springView.setHeader(new DefaultHeader(this.getContext()));
        springView.setFooter(new DefaultFooter(this.getContext()));
        noMessageTip = (TextView) mFragmentView.findViewById(R.id.tv_no_data_tip);


    }

    @Override
    protected void initLocalData() {
        loadMessageListByCache();

    }

    @Override
    protected void initListener() {
        mRefreshLayout.setOnRefreshListener(this);
        messageList.setOnItemClickListener(this);
        springView.setListener(new SpringView.OnFreshListener() {
            @Override
            public void onRefresh() {

            }

            @Override
            public void onLoadmore() {
                messageList(LOAD_COUNT, adapter.getCount(), false);
            }
        });
//        springView.setEnable(false);
        mRefreshLayout.setEnabled(true);

        messageList.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                // 当不滚动时
//                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
//                    // 判断是否滚动到顶部
//                    if (view.getFirstVisiblePosition() == 0) {
//                        View firstVisibleItemView = view.getChildAt(0);
//                        if (firstVisibleItemView != null && firstVisibleItemView.getTop() == 0) {
//                            mRefreshLayout.setEnabled(true);
//                        } else {
//                            mRefreshLayout.setEnabled(false);
//                        }
//                    } else {
//                        mRefreshLayout.setEnabled(false);
//                    }
//                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                mRefreshLayout.setEnabled(false);
                springView.setEnable(false);
                if (firstVisibleItem == 0) {
                    View firstVisibleItemView = view.getChildAt(0);
                    if (firstVisibleItemView != null && firstVisibleItemView.getTop() == 0) {
                        LogUitl.d("ListView", "##### 滚动到顶部 #####");
                        mRefreshLayout.setEnabled(true);
                    }
                } else if ((firstVisibleItem + visibleItemCount) == totalItemCount) {
                    View lastVisibleItemView = view.getChildAt(view.getChildCount() - 1);
                    if (lastVisibleItemView != null && lastVisibleItemView.getBottom() == view.getHeight()) {
                        springView.setEnable(true);
                    }
                }

            }
        });
    }


    public void onClick(View v) {
        switch (v.getId()) {
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        messageList(20, 0, true);
    }

    public void loadMessageListByCache(){
        String uid =  UserManager.getCurrentUser().getID();
        CacheFactory.loadMessageList(uid, new CacheObserver<ArrayList<MessageModel>>() {

            @Override
            public void onNext(ArrayList<MessageModel> value) {
                if (value != null) {
                    adapter.replaceAll(value);
                } else {
                    showNoMessageTip();
                }
            }

        });
    }


    private void messageList(int limit, final int offset, final boolean hasLoading) {
        if (hasLoading) {
            showLoading();
        }
        RequestFactory.messageList(limit, offset, new MessageListMapper(), new RXObserver<ArrayList<MessageModel>>() {

            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(ArrayList<MessageModel> value) {
                if (value != null && value.size() > 0) {
                    if (offset > 0) {
                        adapter.addAll(value);
                    } else {
                        adapter.replaceAll(value);
                        //缓存
                        String uid =  UserManager.getCurrentUser().getID();
                        CacheFactory.cacheMessageList(uid,value);
                    }
                    hideNoMessageTip();
                } else {
                    if (hasLoading) {
                        showNoMessageTip();
                    } else {
                        showSuccessTip("没有更多通知");
                    }
                }
            }

            @Override
            public void onError(Throwable e) {
                if (hasLoading) {
                    dismissLoading();
                } else {
                    mRefreshLayout.setRefreshing(false);
                    springView.onFinishFreshAndLoad();
                }
                resolveException(e);
            }

            @Override
            public void onComplete() {
                if (hasLoading) {
                    dismissLoading();
                } else {
                    mRefreshLayout.setRefreshing(false);
                    springView.onFinishFreshAndLoad();
                }
            }
        });
    }


    private void showNoMessageTip() {
        noMessageTip.setVisibility(View.VISIBLE);
        messageList.setVisibility(View.GONE);
    }

    private void hideNoMessageTip() {
        noMessageTip.setVisibility(View.GONE);
        messageList.setVisibility(View.VISIBLE);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        MessageModel message = adapter.getItem(position);
        if (message != null) {
            if (!message.isRead()) {
                setReadStatus(message);
            }
            redirect(message);
        }
    }

    private void redirect(MessageModel messageModel) {
        if ("1".equals(messageModel.getType()) //1为点赞 2为打赏3为通知 4为评论
                || "2".equals(messageModel.getType())
                || "4".equals(messageModel.getType())) {
            //
            getActivity().startActivity(MessagePostActivity.newInstant(getActivity(), messageModel));
        } else if ("5".equals(messageModel.getType())
                || "6".equals(messageModel.getType())) { //5为举报失败6为举报成功
            getActivity().startActivity(MessageReportActivity.newInstant(getActivity(), messageModel));
        }
    }


    private void setReadStatus(final MessageModel message) {
        RequestFactory.setMessageRead(message.getID(), null, new RXObserver<JSONObject>() {

            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(JSONObject value) {
                message.setRead(true);
                adapter.notifyDataSetHasChanged();
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });


    }

    @Override
    public void onRefresh() {
        messageList(LOAD_COUNT, 0, false);
    }
}
